//
//  WebViewController.m
//  GiganticWhale
//
//  Created by 裴烨烽 on 16/6/27.
//  Copyright © 2016年 Gigantic. All rights reserved.
//

#import "WebViewController.h"
#import <UMAnalytics/MobClick.h>

@interface WebViewController()<GWWebViewDelegate,UIWebViewDelegate>

@end

@implementation WebViewController

+(instancetype)sharedAccountModel{
    static WebViewController *_sharedAccountModel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedAccountModel = [[WebViewController alloc] init];
    });
    
    return _sharedAccountModel;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[WebViewController sharedAccountModel].navigationController setNavigationBarHidden:YES animated:NO];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [[WebViewController sharedAccountModel] createWebView];
    [[WebViewController sharedAccountModel] createAnimationImgView];
    if ([AccountModel sharedAccountModel].appIndex == 1){
        [[WebViewController sharedAccountModel] createHUD];
    }
    [MobClick event:@"打开次数"];
}

-(void)addUmen{
    // 友盟添加打开网页
    NSDictionary *dict = @{@"网站点开次数" : [AccountModel sharedAccountModel].rootModel.link};
    [MobClick event:@"purchase" attributes:dict];
}

#pragma mark - 创建animationView
-(void)createAnimationImgView{
    
    dispatch_main_async_safe(^{
        [WebViewController sharedAccountModel].imgView = [[UIImageView alloc]init];
        [WebViewController sharedAccountModel].imgView.backgroundColor = [UIColor clearColor];
        [WebViewController sharedAccountModel].imgView.frame = CGRectMake(0, 0, kScreenWidth ,kScreenBounds.size.height);
        if (iPhone6_6s){
            [WebViewController sharedAccountModel].imgView.image = [UIImage imageNamed:@"iphone6.jpg"];
        } else if (iPhone6_6sPlus){
            [WebViewController sharedAccountModel].imgView.image = [UIImage imageNamed:@"6p.jpg"];
        } else if (iPhone5){
            [WebViewController sharedAccountModel].imgView.image = [UIImage imageNamed:@"iphone5.jpg"];
        } else if (IS_iPhoneX){
            [WebViewController sharedAccountModel].imgView.image = [UIImage imageNamed:@"iphoneX.jpg"];
        }
        [[WebViewController sharedAccountModel].view addSubview:[WebViewController sharedAccountModel].imgView];
    });
}

#pragma mark 启动菊花
-(void)createHUD{
    [WebViewController sharedAccountModel].activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    [[WebViewController sharedAccountModel].view addSubview:[WebViewController sharedAccountModel].activityIndicator];
    //设置小菊花的frame
    [WebViewController sharedAccountModel].activityIndicator.frame= CGRectMake((kScreenBounds.size.width - 100) / 2., kScreenBounds.size.height / 2. + 100, 100, 100);
    //设置小菊花颜色
    [WebViewController sharedAccountModel].activityIndicator.color = [UIColor grayColor];
    //设置背景颜色
    [WebViewController sharedAccountModel].activityIndicator.backgroundColor = [UIColor clearColor];
    //刚进入这个界面会显示控件，并且停止旋转也会显示，只是没有在转动而已，没有设置或者设置为YES的时候，刚进入页面不会显示
    [WebViewController sharedAccountModel].activityIndicator.hidesWhenStopped = NO;
    [[WebViewController sharedAccountModel].activityIndicator startAnimating];
}


#pragma mark createWebView
-(void)createWebView{
    [WebViewController sharedAccountModel].mainWebView = [[GWWebView alloc]initWithFrame:[WebViewController sharedAccountModel].view.bounds];
    [WebViewController sharedAccountModel].mainWebView.delegate = self;
    [WebViewController sharedAccountModel].mainWebView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [[WebViewController sharedAccountModel].view addSubview:[WebViewController sharedAccountModel].mainWebView];
    
    [WebViewController sharedAccountModel].statusBarView = [[UIView alloc]init];
    [WebViewController sharedAccountModel].statusBarView.backgroundColor = [UIColor clearColor];
    [[WebViewController sharedAccountModel].view addSubview:[WebViewController sharedAccountModel].statusBarView];
    [WebViewController sharedAccountModel].statusBarView.frame = CGRectMake(0, 0, kScreenWidth,[AccountModel sharedAccountModel].statusHeight);
}

// 跳转
-(void)webViewControllerWithAddress:(NSString *)url{
    if (![WebViewController sharedAccountModel].mainWebView){
        [[WebViewController sharedAccountModel] createWebView];
    }
    [[WebViewController sharedAccountModel].mainWebView loadURLString:url];
}


- (void)webViewDidStartLoad:(GWWebView *)webview {
    NSLog(@"页面开始加载");
}

- (void)webView:(GWWebView *)webview shouldStartLoadWithURL:(NSURL *)URL {
    NSLog(@"截取到URL：%@",URL);
    // 1. 删除掉http：//
    NSString *urlStr = URL.absoluteString;
    NSString *panduanStr = @"";
    if ([urlStr hasPrefix:@"http://"]){
        NSString *str1 = [urlStr substringFromIndex:7];//截取掉下标5之前的字符串
        panduanStr = str1;
    } else if ([urlStr hasPrefix:@"https://"]){
        NSString *str1 = [urlStr substringFromIndex:8];//截取掉下标5之前的字符串
        panduanStr = str1;
    }
    // 2.根据尾巴进行切分为数组
    NSArray *panduanArr = [panduanStr componentsSeparatedByString:@"/"];
    // 3. 如果数组对象为2个。且最后一个为空字符串。就进行自带浏览器跳转
    if (panduanArr.count == 2 && [[panduanArr lastObject] isEqualToString:@""]){
        [[WebViewController sharedAccountModel].mainWebView.wkWebView stopLoading];
        [GWTool openURLWithURL:urlStr];
        return;
    }
}

- (void)webView:(GWWebView *)webview didFinishLoadingURL:(NSURL *)URL {
    if ([AccountModel sharedAccountModel].adHasLoaded == NO){
        [AccountModel sharedAccountModel].hasError = YES;
        return;
    }
    
    [self webFinash];
}

-(void)webFinash{
    [AccountModel sharedAccountModel].webHasLoaded = YES;

    [UIView animateWithDuration:.5f animations:^{
        [WebViewController sharedAccountModel].imgView.alpha = 0;
    } completion:^(BOOL finished) {
        [WebViewController sharedAccountModel].imgView.hidden = YES;
    }];
    [[WebViewController sharedAccountModel].activityIndicator stopAnimating];
    [WebViewController sharedAccountModel].activityIndicator.hidden = YES ;
}

-(void)webView:(GWWebView *)webView canOpenUrl:(NSURL *)URL{
    if ([URL.absoluteString hasPrefix:@"mqqwpa"]){
        [GWTool openURLWithURL:URL.absoluteString];
    } else if ([URL.absoluteString hasPrefix:@"weixin"]){
        [[WebViewController sharedAccountModel] screenShot];
        [GWTool openURLWithURL:URL.absoluteString];
    }
}


- (void)webView:(GWWebView *)webview didFailToLoadURL:(NSURL *)URL error:(NSError *)error {
    NSLog(@"加载出现错误");
}

-(void)loadWeb{
    [[WebViewController sharedAccountModel] webViewControllerWithAddress:[AccountModel sharedAccountModel].rootModel.link];
}

-(void)loadUmen{
    
}

-(void)showUpload{
    [[WebViewController sharedAccountModel] addUmen];
    
    CGFloat appVersion = [[GWTool appVersion]floatValue];
    if (appVersion < [AccountModel sharedAccountModel].rootModel.upgrade.version){
        [[UIAlertView alertViewWithTitle:[AccountModel sharedAccountModel].rootModel.upgrade.title message:[AccountModel sharedAccountModel].rootModel.upgrade.content buttonTitles:@[[AccountModel sharedAccountModel].rootModel.upgrade.sure,[AccountModel sharedAccountModel].rootModel.upgrade.cancel] callBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0){
                [GWTool openURLWithURL:[AccountModel sharedAccountModel].rootModel.upgrade.download];
                return ;
            }
        }]show];
    }
    
}

#pragma mark 进行截图
-(void) screenShot{
    UIGraphicsBeginImageContext(kScreenBounds.size);   //self为需要截屏的UI控件 即通过改变此参数可以截取特定的UI控件
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}
@end

